//
//  NetWorkTool.swift
//  LZFPhotoBrowser
//
//  Created by 梁梓烽 on 16/7/23.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType{
    case GET 
    case POST
}

//typealias success (task:NSURLSessionDataTask, result:AnyObject?) -> Void

class NetWorkTools: AFHTTPSessionManager {
 
    //单例
    static let shareInstance : NetWorkTools = {
         let tool = NetWorkTools()
         tool.responseSerializer.acceptableContentTypes?.insert("text/html")
         return tool
    }()
    
}

// MARK: - 封装网络请求
//AnyObject?  可以传任意遵守了AnyObject的对象,默认情况下所有对象都遵守AnyObject协议
extension NetWorkTools {
    func request(requestType:RequestType,url:String,params:[String:AnyObject],finishedBLock:(result:AnyObject?,error:NSError?)->()){
        
        
        //afn成功时候的回调
        let successCallBack = {
            (task:NSURLSessionDataTask, result:AnyObject?) -> Void in
            finishedBLock(result: result, error: nil)
        }
        
        //定义afn发生错误时的回调
        let errorCallBack = {
            (task: NSURLSessionDataTask?, error:NSError) -> Void in
            finishedBLock(result: nil, error:error)
            }
        
        
        //判断是get/post请求
        if requestType == .GET {
            //afn get
            GET(url, parameters: params, progress: nil, success: successCallBack, failure: errorCallBack)
        }
        else
        {
            //afn post
            POST(url, parameters: params, progress: nil, success: successCallBack, failure: errorCallBack)
        }
        
    }
}


// MARK: - 请求首页数据方法
extension NetWorkTools{
    
    func  loadHomeData(offSet:Int,finished:(result:[[String:AnyObject]]? , error:NSError?)->()){
        
    // 1.获取请求的URLString
    let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
    
    // 2.获取请求的参数
    let parameters = ["offset" : "\(offSet)", "limit" : "30", "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"]
    
    
    // 3.发送网络请求
    request(.GET, url: urlString, params: parameters) { (result, error) -> () in
        
        //1.错误校验
        if error != nil{
            finished(result: nil, error: error)
            return
        }
        
        //2.取出数据 AnyObject? --> 字典? --> 解包
        guard let  resultDic = result as? [String:AnyObject]  else {
            finished(result: nil, error: NSError(domain: "data error", code: -1011, userInfo: nil))
            return
        }
        
        //来到这步的话,说明拿到了返回的字典,
        //3.取出字典数组并返回
        
        finished(result: resultDic["data"] as? [[String:AnyObject]], error: nil)
    
        }
       
    }

}
